//
//  SecondaryDetailViewController.m
//  House
//
//  Created by 张垚 on 16/7/12.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "SecondaryDetailViewController.h"
#import "BaseTitleNavigationBar.h"
#import "ImageViewAndLabelButton.h"
#import "RecycleViewCollectionViewCell.h"
#import "IndexMainRecommondTableViewCell.h"
#import "ReuseHouseBaseInfoTableViewCell.h"
#import "ReuseHouseDetailInfoTableViewCell.h"
#import "ReuseCategoryChooseTableViewCell.h"
#import "HouseEvaluateTableViewCell.h"
#import "UnfoldFrameModel.h"
#import "UnfoldModel.h"
#import "NearMapViewController.h"
#import "HouseEvaluateInfoViewController.h"
#import "IndoorMatchTableViewCell.h"
#import "RentHouseDetailModel.h"
#import <UMSocial.h>
#import "House-Swift.h"
#import "RentHouseListNoSlideTableViewCell.h"
#import "SDPhotoBrowser.h"
#import "HouseDetailCharacteristicTableViewCell.h"

@interface SecondaryDetailViewController ()<UITableViewDelegate, UITableViewDataSource, HouseEvaluateTableViewCellDelegate, SDCycleScrollViewDelegate, SDPhotoBrowserDelegate>
//顶部视图
@property (nonatomic, strong) BaseTitleNavigationBar *myBar;
//关注、分享、咨询三个按钮
@property (nonatomic, strong) ImageViewAndLabelButton *attentionButton;
@property (nonatomic, strong) ImageViewAndLabelButton *shareButton;
@property (nonatomic, strong) UIButton *consultButton;
//tableview属性
@property (nonatomic, strong) UITableView *tableView;

//轮播图放大之后的背景图
@property (nonatomic, strong) UIView *backgroundView;
//房评数据
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) RentHouseDetailModel *model;

@property (nonatomic, strong) MBProgressHUD *hud;

@property (nonatomic, strong) NSMutableArray *imageArr;
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;

@property (nonatomic, strong) NSArray *similiarArr;

@end

@implementation SecondaryDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    //顶部视图
    _myBar = [[BaseTitleNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64) WithTitleStr:_model.title];
    [self.view addSubview:_myBar];
    //返回视图添加手势 用于返回
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back:)];
    [_myBar.leftView addGestureRecognizer:tap];
    
    //tableview
    [self initTableView];
    //底部视图
    [self initBottomView];
    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.label.text = @"正在加载数据";
    _hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    _hud.backgroundView.backgroundColor = [UIColor whiteColor];
    _hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    _hud.animationType = MBProgressHUDAnimationZoomIn;
    //数据加载
    [self handleMainData];
    // Do any additional setup after loading the view.
}
#pragma mark - 经纪人房评数据处理
-(void)initLoadData
{
    self.dataArray = [NSMutableArray array];
    NSArray *array  = @[@"维基百科（Wikipedia），是一个基于维基技术的多语言百科全书协作计划，这是一部用多种语言编写的网络百科全书。  维基百科一词取自于该网站核心技术“Wiki”以及具有百科全书之意的共同创造出来的新混成词“Wikipedia”，维基百科是由非营利组织维基媒体基金会负责营运，并接受捐赠。",@"2002年2月，由Edgar Enyedy领导，非常活跃的西班牙语维基百科突然退出维基百科并建立了他们自己的自由百科（Enciclopedia Libre）；理由是未来可能会有商业广告及失去主要的控制权。",@"来看看劳动法克林顿刷卡思考对方卡拉卡斯的楼房卡拉卡斯的疯狂拉萨的罚款 ",@"Apple is supplying this information to help you plan for the adoption of the technologies and programming interfaces described herein for use on Apple-branded products. This information is subject to change, and software implemented according to this document should be tested with final operating system software and final documentation. Newer versions of this document may be provided with future betas of the API or technology.",@"2015年11月1日，英文维基百科条目数突破500万",@"2015年6月15日，维基百科全面采用HTTPS：保护用户敏感信息。"];
    
    for (NSString *str in array) {
        UnfoldModel *model = [[UnfoldModel alloc]init];
        model.contextStr = str;
        model.isFold = NO;//给出初始值
        
        UnfoldFrameModel *frameModel = [[UnfoldFrameModel alloc]init];
        frameModel.model = model;
        [self.dataArray addObject:frameModel];
    }
    
}
//加载数据
- (void)handleMainData {
    _imageArr = [NSMutableArray array];
    _dataArray = [NSMutableArray array];
    _similiarArr = [NSArray array];
    [NetRequest getWithURLString:@"http://aizufang.hrbzjwl.com/tp/api.php/Rent/zuxiang" parameters:@{@"itemid": _itemID, @"type": @"2", @"uid": [UserInfoManager sharedManager].uid} progress:^(NSProgress *progress) {
    } success:^(id response) {
        if ([response[@"flag"] isEqualToString:@"1"]) {
            _hud.label.text = @"加载完毕";
            [_hud hideAnimated:YES afterDelay:1];
            _similiarArr = response[@"gc"];
            NSDictionary *dic = response[@"chuzu"];
            //关注
            if ([[dic[@"follow"] description] isEqualToString:@"0"]) {
                _attentionButton.logoImage.image = [UIImage imageNamed:@"cancelAttention"];
            }else {
                _attentionButton.logoImage.image = [UIImage imageNamed:@"attentionSuccess"];
            }
            _model = [RentHouseDetailModel modelWithDic:dic];
            _myBar.titleLabel.text = [_model.title description];
            
            if ([dic[@"thumb"] isKindOfClass:[NSNull class]]) {
                
            }else {
                NSArray *iamgeArr = dic[@"thumb"];
                for (NSDictionary *imageDic in iamgeArr) {
                    [_imageArr addObject:imageDic[@"thumb"]];
                }
            }
            _cycleScrollView.imageURLStringsGroup = _imageArr;
            
            NSDictionary *remarkDic = dic[@"remark"];
            UnfoldModel *model = [[UnfoldModel alloc]init];
            model.contextStr = [remarkDic[@"intorduce"] description];
            model.isFold = NO;//给出初始值
            UnfoldFrameModel *frameModel = [[UnfoldFrameModel alloc]init];
            frameModel.model = model;
            [self.dataArray addObject:frameModel];
            [_tableView reloadData];
            [MineHistoryManager storeItemID:_itemID withType:7];
        }else {
            _hud.label.text = @"加载失败";
            [_hud hideAnimated:YES afterDelay:1];
        }
        
    } failure:^(NSError *error) {
        _hud.label.text = @"服务器异常";
        [_hud hideAnimated:YES afterDelay:1];
    }];
}

#pragma mark - 底部视图
/* 底部按钮设置 */
- (void)initBottomView {
    UIView *superView = self.view;
    //底部视图上面的横线
    UIView *topView = [[UIView alloc] init];
    [self.view addSubview:topView];
    //分享、关注中间的竖线
    UIView *midView = [[UIView alloc] init];
    [self.view addSubview:midView];
    //分享 关注
    _attentionButton = [[ImageViewAndLabelButton alloc] init];
    _attentionButton.logoNameLabel.text = @"关注";
    _attentionButton.tag = 1;
    [self.view addSubview:_attentionButton];
    [_attentionButton addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
    _shareButton = [[ImageViewAndLabelButton alloc] init];
    _shareButton.logoNameLabel.text = @"分享";
    _shareButton.tag = 2;
    [self.view addSubview:_shareButton];
    [_shareButton addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
    _shareButton.logoImage.image = [UIImage imageNamed:@"shareHouse"];
    _consultButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_consultButton];
    //视图布局
    CGFloat width = kScreenWidth / 4;
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(superView.mas_left);
        make.bottom.equalTo(_attentionButton.mas_top);
        make.height.equalTo(@1);
        make.width.mas_equalTo(kScreenWidth / 2 + 1);
    }];
    topView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
    [midView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_attentionButton.mas_right);
        make.width.equalTo(@1);
        make.height.equalTo(@40);
        make.centerY.equalTo(_attentionButton.mas_centerY);
    }];
    midView.backgroundColor = [UIColor colorWithRed:0.902 green:0.902 blue:0.902 alpha:1.0];
    
    [_attentionButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(superView.mas_left);
        make.bottom.equalTo(superView.mas_bottom);
        make.height.equalTo(@59);
        make.width.mas_equalTo(width);
    }];
    [_shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(midView.mas_right);
        make.bottom.equalTo(superView.mas_bottom);
        make.height.equalTo(@59);
        make.width.mas_equalTo(width);
    }];
    
    [_consultButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(superView.mas_right);
        make.height.equalTo(@60);
        make.left.equalTo(_shareButton.mas_right);
        make.bottom.equalTo(superView.mas_bottom);
    }];
    _consultButton.backgroundColor = [UIColor colorWithRed:1.0 green:0.502 blue:0.0 alpha:1.0];
    [_consultButton setTitle:@"咨询客服" forState:UIControlStateNormal];
    [_consultButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_consultButton addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
    _consultButton.titleLabel.font = [UIFont systemFontOfSize:20 weight:20];
    
}
//底部按钮点击事件
- (void)btn:(ImageViewAndLabelButton *)button {
    if (button.tag == 1) {
        [self attentionHouseActionWithAttentionButton:button];
    } else if (button.tag == 2) {
        //如果需要分享回调，请将delegate对象设置self，并实现下面的回调方法
        [UMSocialData defaultData].extConfig.title = @"爱租房，找房就是找生活";
        //微信
        [UMSocialData defaultData].extConfig.wechatSessionData.shareImage = [UIImage imageNamed:@"appIcon"];
        [UMSocialData defaultData].extConfig.wechatSessionData.url = [NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/index.php/Home/Zufang/xiangqing/id/%@", _itemID];
        
        [UMSocialData defaultData].extConfig.wechatTimelineData.shareImage = [UIImage imageNamed:@"appIcon"];
        [UMSocialData defaultData].extConfig.wechatTimelineData.url = [NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/index.php/Home/Zufang/xiangqing/id/%@", _itemID];
        //QQ
        [UMSocialData defaultData].extConfig.qqData.url = [NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/index.php/Home/Zufang/xiangqing/id/%@", _itemID];
        [UMSocialData defaultData].extConfig.qqData.shareImage = [UIImage imageNamed:@"appIcon"];
        //QQ空间
        [UMSocialData defaultData].extConfig.qzoneData.url = [NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/index.php/Home/Zufang/xiangqing/id/%@", _itemID];
        [UMSocialData defaultData].extConfig.qzoneData.shareImage = [UIImage imageNamed:@"appIcon"];
        
        
        //微博
        [UMSocialData defaultData].extConfig.sinaData.shareImage = [UIImage imageNamed:@"appIcon"];
        
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"57cfcf67e0f55aaf9e002512"
                                          shareText:@"爱租房是一款集租房、买房、二手房交易为一体的APP，随时随地找房，世界从此不陌生"
                                         shareImage:[UIImage imageNamed:@"icon"]
                                    shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToSina,UMShareToQQ, UMShareToQzone]
                                           delegate:nil];
    }else {
        NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",unifyServiceNumber];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}
#pragma mark - 关注功能 用户提示框
- (void)attentionHouseActionWithAttentionButton:(ImageViewAndLabelButton *)button {
    if ([self isLogin]) {
        NSDictionary *submitDic = @{@"uid": [UserInfoManager sharedManager].uid, @"fid": _itemID, @"type": @"2"};
        [NetRequest getWithURLString:@"http://aizufang.hrbzjwl.com/tp/index.php/Api/iosapp/follow_app/" parameters:submitDic progress:^(NSProgress *progress) {
            
        } success:^(id response) {
            if ([response[@"flag"] isEqualToString:@"1"]) {
                button.logoImage.image = [UIImage imageNamed:@"cancelAttention"];
                [self alertMessage:@"取消关注"];
            }else if ([response[@"flag"] isEqualToString:@"2"]) {
                button.logoImage.image = [UIImage imageNamed:@"attentionSuccess"];
                [self alertMessage:@"关注成功"];
            }else {
                [self alertMessage:@"操作失败"];
            }
        } failure:^(NSError *error) {
            [self alertMessage:@"操作失败"];
        }]; 
    }else {
        MineLoginViewController *mineVC = [[MineLoginViewController alloc] init];
        [self.navigationController pushViewController:mineVC animated:YES];
    }
}

- (void)alertMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];
    });
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark - tableView
- (void)initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 124) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[ReuseHouseBaseInfoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([ReuseHouseBaseInfoTableViewCell class])];
    [_tableView registerClass:[ReuseHouseDetailInfoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([ReuseHouseDetailInfoTableViewCell class])];
    [_tableView registerClass:[IndoorMatchTableViewCell class] forCellReuseIdentifier:NSStringFromClass([IndoorMatchTableViewCell class])];
    [_tableView registerClass:[HouseEvaluateTableViewCell class] forCellReuseIdentifier:NSStringFromClass([HouseEvaluateTableViewCell class])];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    [_tableView registerClass:[RentHouseListNoSlideTableViewCell class] forCellReuseIdentifier:NSStringFromClass([RentHouseListNoSlideTableViewCell class])];
    [_tableView registerClass:[HouseDetailCharacteristicTableViewCell class] forCellReuseIdentifier:NSStringFromClass([HouseDetailCharacteristicTableViewCell class])];
    
    
    _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 170) imageURLStringsGroup:_imageArr];
    _cycleScrollView.delegate = self;
    _cycleScrollView.placeholderImage = [UIImage imageNamed:@"placeHolderPic"];
    _tableView.tableHeaderView = _cycleScrollView;
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 11;
}

//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 120;
    }else if (indexPath.row == 2) {
        return 30;
    }else if (indexPath.row == 3) {
        return 160;
    } else if (indexPath.row == 5){
        return 170;
    }else if (indexPath.row == 8) {
        return 100;
    }else if (indexPath.row == 10){
        UnfoldFrameModel *frameModel = [self.dataArray firstObject];
        return frameModel.cellHeight;
    }else if (indexPath.row == 7) {
        return 30;
    }else {
        return 15;
    }
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        ReuseHouseBaseInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ReuseHouseBaseInfoTableViewCell class])];
        cell.model = _model;
        cell.priceNameLabel.text = @"租金";
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.row == 2) {
        HouseDetailCharacteristicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HouseDetailCharacteristicTableViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.currentModel = _model;
        return cell;
        
    }else if (indexPath.row == 3) {
        ReuseHouseDetailInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ReuseHouseDetailInfoTableViewCell class])];
        cell.model = _model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    } else if (indexPath.row == 5)  {
        IndoorMatchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([IndoorMatchTableViewCell class])];
        cell.model = _model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.row == 8)  {
        RentHouseListNoSlideTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([RentHouseListNoSlideTableViewCell class])];
        //取model 赋值给cell
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[_similiarArr firstObject]];
        RentHouseListModel *model = [RentHouseListModel modelWithDic:dic];
        cell.model = model;
        cell.tag = [model.itemid integerValue];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.row == 10) {
        HouseEvaluateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HouseEvaluateTableViewCell class])];
        cell.remarkDic = _model.remark;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //2,设置cell的数据
        UnfoldFrameModel *frameModel = [self.dataArray firstObject];
        cell.frameModel = frameModel;
        cell.delegate = self;
        return cell;
    }
    else {
       static NSString *cellID = @"cellID";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 7) {
            cell.contentView.backgroundColor = [UIColor whiteColor];
            cell.textLabel.text = @"相似房源";
        }else {
          cell.contentView.backgroundColor = [UIColor colorWithRed:0.9528 green:0.9435 blue:0.962 alpha:1.0];
        }
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 8) {
        RentHouseListNoSlideTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        SecondaryDetailViewController *secondaryVC  = [[SecondaryDetailViewController alloc] init];
        secondaryVC.itemID = [NSString stringWithFormat:@"%ld", (long)cell.tag];
        [self.navigationController pushViewController:secondaryVC animated:YES];
    }
}

#pragma mark - 点击事件

//返回手势
- (void)back:(UITapGestureRecognizer *)tap {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - VC delegate
//隐藏 展开文本
-(void)UnfoldCellDidClickUnfoldBtn:(UnfoldFrameModel *)frameModel
{
    UnfoldModel *model = frameModel.model;
    model.isFold = !model.isFold;
    frameModel.model = model;//这句话很关键，要把值设置回来，因为其setModel方法中会重新计算frame
    [_tableView reloadData];
}


//拨打经纪人电话 如果经纪人没有电话的话 直接联系客服
- (void)callAgentPhoneNumber {
    if ([_model.remark[@"mobile"] isKindOfClass:[NSNull class]]) {
        NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",unifyServiceNumber];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }else {
        NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",_model.remark[@"mobile"]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    //创建SDPhotoBrowser实例
    SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
    browser.sourceImagesContainerView = [_cycleScrollView.subviews firstObject];
    browser.imageCount = _imageArr.count;
    browser.currentImageIndex = index;
    browser.delegate = self;
    [browser show]; // 展示图片浏览器
    
    
}

// 返回临时占位图片（即原来的小图）

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index {
    UIImage *myImage = [UIImage imageNamed:@"placeHolderPic"];
    return myImage;
}

// 返回高质量图片的url

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index {
    NSURL *picUrl = [NSURL URLWithString:_imageArr[index]];
    return picUrl;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
